<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request; //命名空间的三元素：常量，方法和类
use App\Http\Requests;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Contracts\Encryption\DecryptException;
// use Illuminate\Support\Facades\Input;
// use Illuminate\Support\Facades\Validator;
use Input;
use DB;
use Session;
use App\Http\Model\Admin;
use App\Http\Model\User;


class UserController extends Controller{
    public function Login(Request $request)
    {
        $name=$request->get('yhm');
        $password=md5($request->get('mm'));
        $captcha=$request->get('yzm');
        if(strtolower($captcha)==strtolower(session()->get('captcha','')))
        { 
            $result=Admin::where('name',$name)->where('password',$password)->first();

            if($result!=null)
            {
                session(['result'=>$result]);
                session(['name'=>$name]);
    
                return redirect('admin/shopym');
            }else{
                
                return redirect()->back()->with('message','用户名或密码错误');
                
            }
        }
        else{
           
            return redirect()->back()->with('message','验证码错误');
        }  
            
        
    }

    // 退出系统，清空session
    public function Quit(){
        session(['result'=>null]);
        return redirect('admin/login');
    }



     // 修改密码
     public function Pass(){
        if($input = Input::all()){
            //定义每个字段的要求
            $rules = [
            'password'=>'required', 
            'newpass'=>'required|between:6,20|confirmed', 
                //不能为空;字符在6-20;与确认密码进行验证；
            ];
            //重新定义错误信息，格式： '字段.属性'=>'信息'
            $messages = [
                'password.required'=>'原密码不能为空', 
                'newpass.required'=>'新密码不能为空', 
                'newpass.between'=>'新密码6-20位',
                'newpass.confirmed'=>'新密码与确认密码不一致'
            ];
            $validator = Validator::make($input,$rules,$messages);
            //利用$validator进行验证，如果新密码与确认密码一致，将获取输入的原密码与数据库中的密码比较，若密码相等，将通过验证，更新为新密码
            if($validator->passes()){
                $user = Admin::first();
                $pass = Crypt::decrypt($user->password);
                if($pass==$input['password']){
                    $user->password = Crypt::encrypt($input['newpass']);
                    $user->update();
                    return back()->with('errors','密码修改成功！'); 
                    //若原密码错误，将返回一个变量到errors中，只是一个字符串
                    return back()->with('errors','原密码错误');
                }
            }else{
                //若原密码、确认密码没有通过验证，则利用withErrroes($validator)保存错误信息到errors对象中，并返回到pass.blade.php,所以pass.blade.php需要将其接收
                //dd($validator->errors()->all());
                return back()->withErrors($validator);
            }

        }else{
            return view('admin/user/pass');
        }
             
    }
}